<template>
	<view class="message-item"
		:class="{'current':currentLongpressMsgId == messageInfo.id,'sender':isSender,'receiver':!isSender}"
		v-if="!isImageError">
		<view class="message-time" v-if="isShowDate">
			{{$utils.messageTimeFormat(Number(messageInfo.time))}}
		</view>
		<view class="withdraw-message-container" v-if="messageType == 'withdraw'">
			{{isSender?'您撤回了一条消息':`${messageInfo.ext.userName}撤回了一条消息`}}
		</view>
		<serviceEvaluation v-else-if="messageType == 'service_evaluation'" @toEvaluation="toEvaluation" />
		<!-- <evaluationMessage v-else-if="messageType == 'text'" v-on="$listeners" :id="messageInfo.id"/> -->
		<view class="message-main" v-else>
			<!-- 用户头像 -->
			<view class="user-avatar-container">
				<img class="user-avatar" mode="aspectFill" style="width: 100%; height:100%;" :src="userAvatar"
					width="100%" height="100%">
				</img>
			</view>
			<!-- 信息内容主体 -->
			<view class="message-content-main">
				<!-- 用户名 -->
				<view class="user-name">
					<!-- {{orderDetail?orderDetail.lawyer_name:messageInfo.ext.userName}} -->
					{{userName}}
				</view>
				<view class="message-content-container">
					<!-- 消息内容，不同消息种类更改此模块 -->
					<!-- 文本消息 -->
					<view class="message-content" v-if="messageType == 'text'"
						v-html="$utils.parseEmoji(messageInfo.data)" @longpress="onLongTapMessage">
					</view>
					<!-- 图片消息 -->
					<view class="message-content img-msg" v-else-if="messageType == 'image'"
						@longpress="onLongTapMessage">
						<u-image :src="messageInfo.url" border-radius="10" width="300" lazy-load :height="imageHeight"
							fade show-loading mode="widthFix" @click="previewImage(messageInfo.url)"
							@load="imgMsgLoadSuccess" @error="onImageError">
							<u-loading slot="loading"></u-loading>
						</u-image>
					</view>
					<!-- 文件消息 -->
					<view class="message-content" v-else-if="messageType == 'file'" @longpress="onLongTapMessage"
						@click="onClickFileMsg(messageInfo.customExts.url)">
						<view class="file-message-container">
							<view class="file-info-wrapper">
								<view class="file-name">
									{{messageInfo.customExts.filename}}
								</view>
								<view class="file-size">
									{{$utils.formatBytes(messageInfo.customExts.filesize,2)}}
								</view>
							</view>
							<view class="file-icon-wrapper">
								<image :src="getFileIcon" class="file-icon"></image>
							</view>
						</view>
					</view>
					<!-- 语音信息 -->
					<view class="message-content" v-else-if="messageType == 'voice'" @click="playVoice"
						@longpress="onLongTapMessage" :style="{'width':`${messageInfo.length*8+150}rpx`}">
						<view class="voice-message-container">
							<image
								:src="isVoicePlaying?require(`@/pages_chat/assets/image/chat/voice.gif`):require(`@/pages_chat/assets/image/chat/voice-icon.png`)"
								class="voice-icon"></image>
							</image>
							<view class="voice-time">
								{{messageInfo.length}}"
							</view>
						</view>
					</view>
					<!-- 定位消息 -->
					<view class="message-content" v-else-if="messageType == 'location'" @click="openLocation"
						@longpress="onLongTapMessage">
						<view class="location-message-container">
							<view class="location-ifno-wrapper">
								<view class="location-info-name">
									{{messageInfo.customExts.name}}
								</view>
								<view class="location-info-address">
									{{messageInfo.customExts.address}}
								</view>
							</view>
							<view class="location-icon-wrapper">
								<i class="iconfont icon-location" />
							</view>
						</view>
					</view>
					<!-- 视频消息 -->
					<view class="video-message-container" v-else-if="messageType == 'video'" :class="setVideoViewType"
						@click="jumpPlayVideo" @longpress="onLongTapMessage">
						<u-image width="100%" height="100%"
							:src="decodeURIComponent(messageInfo.customExts.url)+`?x-oss-process=video/snapshot,t_0,f_jpg`"
							mode="aspectFill">
						</u-image>
						<view class="video-play-icon-container">
							<u-icon name="play-right-fill" size="40"></u-icon>
						</view>
						<view class="video-duration-container">
							{{$utils.durationFormat(messageInfo.customExts.duration)}}
						</view>
					</view>
					<!-- 消息状态 -->
					<view class="message-stuaus">
						<!-- 文件上传进度条 -->
						<u-icon name="checkmark-circle-fill" color="#5ac725" size="40" v-if="isDownloadSuccess">
						</u-icon>
						<u-icon name="error-circle-fill" color="#f56c6c" size="40" v-if="messageInfo.error">
						</u-icon>
						<view class="loading"
							v-if="(messageType == 'image'&&imageLoadimg)||isDownloadShow||messageInfo.stautus == 'sending'">
							<u-loading />
							<view class="progress" v-if="progress>=0">{{progress}}%</view>
						</view>

					</view>
				</view>
				<messageMenu style="position: absolute;" :isSender="isSender"
					:isMsgMenuShow="messageInfo.id == currentLongpressMsgId" :msgType="messageType" @share="share"
					@collect="collect" @save="save" @copy="copy" @withdraw="withdraw" />
			</view>
		</view>
	</view>
</template>

<script>
	const fileSystemManager = wx.getFileSystemManager();
	// import evaluationMessage from "./components/evaluation-message/evaluationMessage.vue";
	import messageMenu from "./components/message_menu/messageMenu.vue";
	import serviceEvaluation from "../../components/service-evaluation/serviceEvaluation.vue";
	export default {
		data() {
			return {
				downloadTask: null,
				progress: -1,
				isImageError: false,
				imageLoadimg: true,
				innerAudioContext: null,
				isDownloadShow: false,
				isDownloadSuccess: false,
				tempFilePath: '',
				localFilePath: '',
				isVoicePlaying: false,
				maxImageWidth: 300,
				allowType: {
					doc: true,
					xls: true,
					ppt: true,
					pdf: true,
					docx: true,
					xlsx: true,
					pptx: true,
				},
			}
		},
		components: {
			// evaluationMessage
			messageMenu,
			serviceEvaluation
		},
		created() {
			//this.innerAudioContext.autoplay = true;
		},
		mounted() {
			this.$nextTick(() => {
				if (this.messageType == 'voice') {
					console.log('是音频消息>>>>>>>>>>>>>>>', this.messageInfo)
					this.innerAudioContext = uni.createInnerAudioContext();
					this.innerAudioContext.src = this.messageInfo.url;
					this.innerAudioContext.onCanplay(() => {
						this.isDownloadShow = false;
					})
					this.innerAudioContext.onPlay(() => {
						this.isDownloadShow = false;
						this.isVoicePlaying = true;
					})
					this.innerAudioContext.onWaiting(() => {
						this.isDownloadShow = true;
					})
					this.innerAudioContext.onStop(() => {
						this.isDownloadShow = false;
						this.isVoicePlaying = false;
					})
					this.innerAudioContext.onError((errCode) => {
						if (errCode == '10002') {
							this.$showToast('当前网络不佳，播放失败')
						}
					})
					this.innerAudioContext.onEnded(() => {
						this.isVoicePlaying = false;
						this.isDownloadShow = false;
					})
				} else if (this.messageType == 'file') {
					fileSystemManager.access({
						path: `${wx.env.USER_DATA_PATH}/${this.fileCode}.${this.fileType}`,
						success: (res) => {
							console.log('查询到本地文件>>>>>>>>>>>>>>>>>', res);
							this.isDownloadSuccess = true;
							this.localFilePath =
								`${wx.env.USER_DATA_PATH}/${this.fileCode}.${this.fileType}`;
						}
					})
				}

			})
		},
		computed: {
			userName() {
				if (this.consultDetail && !this.isCustomer) {
					return '小律在线专员'
				} else if (this.orderDetail && !this.isCustomer) {
					return this.orderDetail.lawyer_name
				} else {
					return this.messageInfo.ext.userName
				}
			},
			userAvatar() {
				if (this.consultDetail && !this.isCustomer) {
					return require('@/pages_chat/assets/image/chat/cs-avatar.png')
				} else if (this.orderDetail && !this.isCustomer) {
					return this.orderDetail.lawyer_avatar
				} else {
					return this.messageInfo.ext.userAvatar
				}
			},
			//消息类型
			messageType() {
				return this.messageInfo.ext.messageType
			},
			//该消息是否是群聊消息
			isGroup() {
				return this.messageInfo.type.toLowerCase() == 'groupchat';
			},
			//该消息是否是当前用户发送
			isSender() {
				return this.messageInfo.from == uni.IM.userId
			},
			isCustomer() {
				console.log('message,this.consultDetail>>>>>>>>>>>>>>>>>>', this.consultDetail);
				if (!this.orderDetail && !this.consultDetail) {
					return false
				} else if (this.consultDetail && this.consultDetail.customer_phone == this.messageInfo.from) {
					return true
				} else if (this.orderDetail && this.orderDetail.customer_phone == this.messageInfo.from) {
					return true
				}
			},
			//该视频消息是横着拍的还是竖着拍的设置样式
			setVideoViewType() {
				if (this.messageType != 'video' || !this.messageInfo.customExts.width || !this.messageInfo.customExts
					.height) {
					return
				}
				return this.messageInfo.customExts.width > this.messageInfo.customExts.height ? 'row' : 'colum'
			},
			// //文件消息的文件类型
			fileType() {
				if (this.messageType != 'file') {
					return ''
				}
				const fileType = this.messageInfo.customExts.filename.split('.')[this.messageInfo.customExts.filename
					.split(
						'.').length - 1];
				return fileType.toLowerCase()
			},
			// //设置文件消息的图标
			getFileIcon() {
				if (this.fileType == 'doc' || this.fileType == 'docx') {
					return require('@/pages_chat/assets/image/chat/docm.png')
				} else if (this.fileType == 'xls' || this.fileType == 'xlsx') {
					return require('@/pages_chat/assets/image/chat/xls.png')
				} else if (this.fileType == 'ppt' || this.fileType == 'pptx') {
					return require('@/pages_chat/assets/image/chat/ppt.png')
				} else if (this.fileType == 'pdf') {
					return require('@/pages_chat/assets/image/chat/pdf.png')
				} else {
					return require('@/pages_chat/assets/image/chat/file-icon.png');
				}
			},
			fileCode() {
				if (this.messageType != 'file') {
					return
				}
				return this.messageInfo.customExts.url.split('.')[this.messageInfo.customExts.url.split('.').length - 2]
					.split('/')[this.messageInfo.customExts.url.split('.')[this.messageInfo.customExts.url.split('.')
						.length - 2].split('/').length - 1];
			},
			imageHeight() {
				if (this.messageType != "image") {
					return;
				} else {
					const imageHeightRpx = 750 * this.messageInfo.height / 375;
					const imageWidthRpx = 750 * this.messageInfo.width / 375;
					console.log(imageHeightRpx);
					const percentage = this.maxImageWidth / imageWidthRpx;
					return parseInt(imageHeightRpx * percentage);
				}
			},
		},
		props: {
			//消息详情信息
			messageInfo: {
				type: Object,
				required: true,
			},
			//是否显示日期
			isShowDate: {
				type: Boolean
			},
			currentLongpressMsgId: {
				type: String,
			},
			orderDetail: {
				type: Object
			},
			consultDetail: {
				type: Object,
			}
		},
		beforeDestroy() {
			if (this.messageType == 'voice')
				this.innerAudioContext.destroy();
		},
		methods: {
			toEvaluation() {
				console.log(this.messageInfo)
				this.$emit('toEvaluation', {
					taskCode: this.messageInfo.ext.task_code,
					evaluateId: this.messageInfo.ext.evaluate_id,
				})
			},
			onImageError() {
				this.isImageError = true;
			},
			onClickFileMsg(url) {
				if (this.isDownloadSuccess && this.localFilePath) {
					this.openLocalFile(this.localFilePath);
				} else {
					uni.showActionSheet({
						itemList: ['预览文件', '保存到本地'],
						success: async (res) => {
							if (res.tapIndex == 0) {
								if (this.tempFilePath) {
									this.openLocalFile(this.tempFilePath)
								} else {
									await this.downloadFile(url);
									this.openLocalFile(this.tempFilePath)
								}
							} else {
								await this.downloadFile(url);
								await this.saveFile();
							}
						},
					});
				}
			},
			saveFile() {
				return new Promise((resolve, reject) => {
					uni.saveFile({
						tempFilePath: this.tempFilePath,
						filePath: `${wx.env.USER_DATA_PATH}/${this.fileCode}.${this.fileType}`,
						success: (result) => {
							//设置当前消息的本地文件临时路径，用于预览文件
							this.localFilePath = result.savedFilePath;
							this.tempFilePath = '';
							this.$showToast('保存成功');
							//显示下载成功的图标
							this.isDownloadSuccess = true;
							//将文件的本地路径和保存到本地用于下次进入页面判断已下载该文件
							// this.saveFiletoLocal(result.savedFilePath);
							resolve()
						},
						fail: () => {
							this.$showToast('保存失败');
							reject();
						}
					})
				})

			},
			//下载文件
			downloadFile(url) {
				return new Promise((resolve, reject) => {
					if (this.isDownloadShow) {
						this.downloadTask.abort();
						this.isDownloadShow = false;
						this.progress = -1;
					} else {
						this.isDownloadShow = true;
						this.downloadTask = wx.downloadFile({
							url,
							success: (res) => {
								this.tempFilePath = res.tempFilePath;
								this.isDownloadShow = false;
								resolve();
							},
							fail: (err) => {
								if (err.errMsg == 'downloadFile:fail abort') {
									this.$showToast('已取消下载')
									reject(true);
								} else {
									this.$showToast('下载失败')
									reject(false);
								}
								this.progress = -1;
								this.isDownloadShow = false;
							}
						})
						this.downloadTask.onProgressUpdate((res) => {
							this.progress = res.progress;
						})
					}
				})
			},
			//预览已下载的文件
			openLocalFile(filePath) {
				if (this.fileType in this.allowType) {
					uni.openDocument({
						filePath,
					})
				} else {
					this.$showToast(`暂不支持预览${this.fileType}类型文件`)
				}

			},
			//预览图片
			previewImage(url) {
				console.log(url)
				uni.previewImage({
					urls: [url],
				})
			},
			//图片加载完毕，滚动到底部
			imgMsgLoadSuccess() {
				// this.$emit('imgMsgLoadSuccess');
				this.imageLoadimg = false;
			},
			//打开定位信息详情
			openLocation() {
				const {
					latitude,
					longitude,
					name,
					address
				} = this.messageInfo.customExts;
				uni.openLocation({
					latitude,
					longitude,
					name,
					address,
				});
			},
			//将文件的本地路径和保存到本地用于下次进入页面判断已下载该文件
			saveFiletoLocal(localFilePath) {
				//生成本地文件路径对象
				const file = {
					...this.messageInfo.customExts,
					localFilePath,
					id: this.messageInfo.id,
				}
				//判断该用户本地有没有本地文件数组
				if (!this.localFile) {
					this.$u.localSave('localFile', [file]);
				} else {
					this.$u.localSave('localFile', [...this.localFile, file]);
				}
			},
			//二次进入聊天页面，查看当前文件消息有没有被下载在本地
			viewLocalFiles() {
				//本地连文件数组都是空的，不用判断了，return
				if (!this.localFile) {
					return
				}
				//因为是根据消息id存在本地的，所以根据id找本地有没有下载该文件
				const localFile = this.localFile.find(item => {
					return item.id == this.messageInfo.id
				})
				//本地有下载该文件
				if (localFile) {
					console.log('本地有下载该文件>>>>>>>>>>>>>>>>>>>', localFile)
					//显示文件下载成功图标
					this.isDownloadSuccess = true;
					//将用于预览的途径设置为该路径
					this.localFilePath = localFile.localFilePath;
				}
			},
			playVoice() {
				if (this.isVoicePlaying) {
					this.innerAudioContext.stop();
				} else {
					this.$emit('allVoiceStopPlay')
					setTimeout(() => {
						this.innerAudioContext.play();
					}, 100)

				}
			},
			//跳转到播放视频页面
			jumpPlayVideo() {
				this.$u.route(`/pages_chat/video/video?url=${this.messageInfo.customExts.url}`)
			},
			//停止播放，点击某一语音时其他语音要停止播放
			stopPlayVideo() {
				if (this.messageType == 'voice') {
					this.innerAudioContext.stop();
				}
			},
			saveNetImageTolocal(url) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: url,
						success: (result) => {
							uni.saveImageToPhotosAlbum({
								filePath: result.path,
								success: () => {
									resolve()
								},
								fail: () => {
									reject()
								}
							});
						},
						fail: () => {
							reject()
						}
					});
				})
			},
			onLongTapMessage() {
				console.log('长按消息')
				// if (!this.isSender) {
				// 	return
				// }
				this.$emit('showMsgMenu', this.messageInfo.id);
			},
			async share() {
				if (this.isDownloadShow) {
					this.downloadTask.abort();
					this.isDownloadShow = false;
					this.progress = -1;
					return
				}
				let url, filename;
				if (this.messageType == 'image') {
					url = this.messageInfo.url;
				} else if (this.messageType == 'file') {
					url = this.messageInfo.customExts.url;
					filename = this.messageInfo.customExts.filename;
				} else if (this.messageType == 'video') {
					url = this.messageInfo.customExts.url;
				}
				try {
					if (this.tempFilePath || this.localFilePath) {
						console.log(this.tempFilePath || this.localFilePath)
						await this.$wx.shareFile(this.tempFilePath || this.localFilePath, this.messageType, filename);
						this.$showToast('转发成功');
					} else {
						this.isDownloadShow = true;
						this.$showToast('下载完毕即可转发');
						// const {
						// 	tempFilePath
						// } = await this.$wx.downloadFile(url);
						this.downloadTask = wx.downloadFile({
							url,
							success: async (res) => {
								this.tempFilePath = res.tempFilePath;
								this.isDownloadShow = false;
								await this.$wx.shareFile(res.tempFilePath, this.messageType, filename);
								this.$showToast('转发成功');
							},
							fail: (err) => {
								if (err.errMsg == 'downloadFile:fail abort') {
									this.$showToast('已取消下载')
								} else {
									this.$showToast('下载失败')
								}
								this.progress = -1;
							}
						})
						this.downloadTask.onProgressUpdate((res) => {
							this.progress = res.progress;
						})
					}
				} catch (e) {
					console.log(e)
					// this.$showToast('转发失败');
				}
			},
			async collect() {
				if (this.isDownloadShow) {
					this.downloadTask.abort();
					this.isDownloadShow = false;
					this.progress = -1;
					return
				}
				let url, filename;
				if (this.messageType == 'image') {
					url = this.messageInfo.url;
				} else if (this.messageType == 'file') {
					url = this.messageInfo.customExts.url;
					filename = this.messageInfo.customExts.filename;
				} else if (this.messageType == 'video') {
					url = this.messageInfo.customExts.url;
				}
				try {
					if (this.tempFilePath || this.localFilePath) {
						console.log(this.tempFilePath || this.localFilePath)
						await this.$wx.collectFile(this.tempFilePath || this.localFilePath, this.messageType,
							filename);
						this.$showToast('收藏成功');
					} else {
						this.isDownloadShow = true;
						this.$showToast('下载完毕即可收藏');
						// const {
						// 	tempFilePath
						// } = await this.$wx.downloadFile(url);
						this.downloadTask = wx.downloadFile({
							url,
							success: async (res) => {
								this.tempFilePath = res.tempFilePath;
								this.isDownloadShow = false;
								await this.$wx.collectFile(res.tempFilePath, this.messageType, filename);
								this.$showToast('转发成功');
							},
							fail: (err) => {
								if (err.errMsg == 'downloadFile:fail abort') {
									this.$showToast('已取消下载')
								} else {
									this.$showToast('下载失败')
								}
								this.progress = -1;
							}
						})
						this.downloadTask.onProgressUpdate((res) => {
							this.progress = res.progress;
						})
					}
				} catch (e) {
					console.log(e)
					// this.$showToast('转发失败');
				}
			},
			async save() {
				let url = this.messageType == 'image' ? this.messageInfo.url : this.messageInfo.customExts.url;
				if (this.messageType == 'file') {
					if (this.tempFilePath) {
						await this.saveFile();
					} else {
						await this.downloadFile(url);
						await this.saveFile();
					}
				} else if (this.messageType == 'image') {
					this.isDownloadShow = true;
					const {
						tempFilePath
					} = await this.$wx.downloadFile(url);
					this.tempFilePath = tempFilePath;
					uni.saveImageToPhotosAlbum({
						filePath: tempFilePath,
						success: () => {
							this.$showToast('已保存到相册')
							this.isDownloadShow = false;
						},
						fail: () => {
							this.$showToast('保存失败')
							this.isDownloadShow = false;
						}
					});
				} else if (this.messageType == 'video') {
					this.isDownloadShow = true;
					const {
						tempFilePath
					} = await this.$wx.downloadFile(url);
					this.tempFilePath = tempFilePath;
					uni.saveVideoToPhotosAlbum({
						filePath: tempFilePath,
						success: () => {
							this.$showToast('已保存到相册')
							this.isDownloadShow = false;
						},
						fail: () => {
							this.$showToast('保存失败')
							this.isDownloadShow = false;
						}
					});
				}
			},
			copy() {
				uni.setClipboardData({
					data: this.messageInfo.data,
					success: () => {
						this.$showToast('复制成功')
					}
				});
			},
			withdraw() {
				uni.showModal({
					title: '撤回确认',
					content: '是否确认撤回该消息',
					success: (res) => {
						if (res.confirm) {
							const time = +new Date();
							if (time - this.messageInfo.time > 120000) {
								return this.$showToast('已超过2分钟不能撤回');
							}
							this.$emit('withdrawMsg', this.messageInfo);
						} else if (res.cancel) {
							this.$emit('showMsgMenu', '');
						}
					},
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	@import "./messageItem.scss";
</style>
